package com.LeetCode.why516;

public class LongestPalindromicSubsequence {
    public int longestPalindromeSubseq(String s) {
        //这个问题是最长回文子序列！！！！！！！！Subsequence
        //不是最长回文子串！！！！！！！！SubString
        //明显DP问题
//p[i][j]: the longest palindromic subsequence's length of substring(i, j)
//State transition:
//p[i][j] = p[i+1][j-1] + 2 if s.charAt(i) == s.charAt(j)
//otherwise, p[i][j] = Math.max(p[i+1][j], p[i][j-1])
//Initialization: dp[i][i] = 1
        //注意循环的方向

        int len = s.length();
        int[][] p = new int[len][len];
        for (int i = len - 1; i >= 0; i--) {
            p[i][i] = 1;
        }
        for (int i = len - 1; i >= 0; i--) {
            for (int j = i + 1; j < len; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    p[i][j] = p[i + 1][j - 1] + 2;
                } else {
                    p[i][j] = Math.max(p[i + 1][j], p[i][j - 1]);
                }
            }
        }
        return p[0][len - 1];
    }

}
